#include "File.h"
#include "ObjMesh.h"
#include "TextureManager.h"
#include "ReportError.h"
#include "StringUtil.h"
#include "LoadScreen.h"
#include <string>
#include <iostream>
#include "btBulletDynamicsCommon.h"
#include <gl/glut.h>


ObjMesh::ObjMesh()
{
	
	m_totalVerts = 0;
	m_coords.reserve(3000);
	m_normals.reserve(3000);
	m_uvs.reserve(3000);
	
}
std::vector<Vec3f>* ObjMesh::GetCoords()
{
	return &m_coords;
}

Faces* ObjMesh::GetFaces()
{
	return &m_faces;
}

int ObjMesh::GetTotalVerts()
{
	return m_totalVerts;
}

bool ObjMesh::Load(const std::string& filename)
{
	File f;

	// open file - ok?
	if (!f.OpenRead(filename))
	{
		ReportError("Couldn't open the file: " + filename);
		return false;
	}

	//loop until no more lines
	std::string line;
	while (f.GetString(&line))
	{
		TheLoadScreen::Instance()->IncrementDraw();
		
		//Draw the load state?
		//TheLoadState::Instance()->Draw();
		//print out the current line
		
		//Strings - typedef'd vector of strings
		Strings strs = Split(line, ' ');
		
		if (strs[0] == "vn")
		{
			//this is a normal, we want to store it in m_normals
			m_normals.push_back(ToVec3(strs));
		}
		else if (strs[0] == "vt")
		{
			//this is a UV, we want to store it in m_uvs
			m_uvs.push_back(ToVec2(strs));
		}
		else if (strs[0] == "v")
		{
			//this is a coord, we want to store it in m_coords
			Vec3f vec = ToVec3(strs);
			m_totalVerts += 3;

			m_coords.push_back(vec);

			
		}
		else if (strs[0] == "f")
		{
			//This is a face line
			Face f = ToFace(strs);

			//store this face in a vector
			m_faces.push_back(f);
		}
		else if (strs[0] == "mtllib")
		{
			
		}
	}
	return true;
}


void ObjMesh::Draw()
{
	glBegin(GL_TRIANGLES);
		for (unsigned int i = 0; i < m_faces.size(); i++)
		{
			Face f = m_faces[i];
			
			int indexCoord1 = f.m_pointIndex[0];
			Vec3f coord1 = m_coords[indexCoord1];
	
			int indexCoord2 = f.m_pointIndex[1];
			Vec3f coord2 = m_coords[indexCoord2];
	
			int indexCoord3 = f.m_pointIndex[2];
			Vec3f coord3 = m_coords[indexCoord3];

			Vec3f normal1 = m_normals[f.m_normalIndex[0]];
			Vec3f normal2 = m_normals[f.m_normalIndex[1]];
			Vec3f normal3 = m_normals[f.m_normalIndex[2]];

			Vec2f uv1 = m_uvs[f.m_uvIndex[0]];
			Vec2f uv2 = m_uvs[f.m_uvIndex[1]];
			Vec2f uv3 = m_uvs[f.m_uvIndex[2]];

			glTexCoord2f(uv1.X, uv1.Y);
			glNormal3f(normal1.X, normal1.Y, normal1.Z);
			glVertex3f(coord1.X, coord1.Y, coord1.Z);

			glTexCoord2f(uv2.X, uv2.Y);
			glNormal3f(normal2.X, normal2.Y, normal2.Z);
			glVertex3f(coord2.X, coord2.Y, coord2.Z);

			glTexCoord2f(uv3.X, uv3.Y);
			glNormal3f(normal3.X, normal3.Y, normal3.Z);
			glVertex3f(coord3.X, coord3.Y, coord3.Z);
		}
	glEnd();
}